﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using BrainTechLLC;
using System.Threading;
using BrainTechLLC.ThreadSafeObjects;

namespace ImageAppDataModels
{
    public static partial class FileLocking
    {
        public static ThreadSafeLookup<string, string> LockedFiles = new ThreadSafeLookup<string, string>();
        public static ThreadSafeCounter TotalCyclesMissedDueToFileLock = new ThreadSafeCounter();

        public static void GetFileLock(string fileName)
        {
        TryAgain:

            while (LockedFiles.ContainsKey(fileName))
            {
                TotalCyclesMissedDueToFileLock.Increment();
                Debug.WriteLine("Waiting for lock for file " + fileName);
                Thread.Sleep(20);
            }

            if (!LockedFiles.Add(fileName, fileName))
            {
                goto TryAgain;
            }
        }

        public static void ReleaseFileLock(string fileName)
        {
            LockedFiles.Remove(fileName);
        }        
    }
}
